<?php
class DbAccess
{
	protected  $prefix="";
	protected  static  $connection;
	protected  static  $client_count=0;
	protected $dbname;
	protected $charset="UTF-8";
	protected $last_select_sql;
	//单例模式
	public function __construct($param)
	{
		$this->dbname=$param["dbname"];
		if(!empty($param["prefix"]))
		{
			$this->prefix=$param["prefix"];
		}
		if(isset($param["charset"]))
		{
			$this->charset=$param["charset"];
		}
		if(empty(self::$connection))
		{
			$this->getInstance($this->dbname);
		}
		self::$client_count++;
	}
	
	//如果所有的对象已经释放，则释放数据库连接
	public function __destruct()
	{
		self::$client_count--;
		if(self::$client_count==0)
		{
		  self::$connection->close();
		}
	}
	private  function getInstance($dbname)
	{
		self::$connection=new com("adodb.connection"); 
		self::$connection->open("driver={Microsoft Access Driver (*.mdb)};dbq=$dbname"); 
		self::$connection->errors->clear();
	}
	//参数SQL不能包含select如： * from member;
	public function select($sql,$sqlcount=false)
	{
		$result=array();
		$this->last_select_sql=$sql;
		$sql_front="select ";
		$sql=$sql_front.$sql;
		$sql_result=self::$connection->execute($sql); 
		while (!$sql_result->eof)
		{
			
			for ($i=0;$i<$sql_result->fields->count;$i++)
			{
				$row[$sql_result->fields[$i]->name]=iconv("GBK","utf-8",$sql_result->fields[$i]->value);
			}
			$result[]=$row;
			$sql_result->movenext();  
		}
		return $result;
	}
	
	public function getLastQueryTotal()
	{
		$sql=$this->last_select_sql;
		$sql=substr($sql,stripos($sql,"from"));
		$sql=" count(*)  as c ".$sql;
		$sql=$this->select($sql);
		$sql=$sql[0];
		$sql=$sql["c"];
		return $sql;
	}
	
	public function insert($data,$table)
	{
		$rs = new com("ADODB.Recordset");

		$rs->Open($table, self::$connection, 1, 2, 2);
        $rs->AddNew();
        foreach ($data as $key=>$value)
        {
        	$rs->fields[$key] = iconv("utf-8","GBK",$value);
        }
        $rs->Update();
        $last_id = $rs->fields["id"]->value;
        $rs->close();
        return $last_id;
	}
	
	public function delete($sql)
	{
		self::$connection->execute($sql,$affected);
		return $affected;
	}
	
	public function update($data,$where,$table)
	{
		$sql="update $table set ";
		foreach ($data as $field=>$value)
		{
			if($field!="id")
			{
				$sql.=" $field='$value',";
			}
		}
		$sql=substr($sql,0,strlen($sql)-1);
		$sql.=' where '.$where;
		self::$connection->execute($sql,$affected);
		return $affected;
	}
	
	public function startTransaction()
	{
		self::$connection->BeginTrans();
	}
	
	public function getError()
	{
		$errors=self::$connection->errors;
		foreach ($errors as $e)
		{
			return  $e->description;
		}
	}
	
	public function rollBack()
	{
		self::$connection->RollbackTrans();
	}
	
	public function commit()
	{
		self::$connection->CommitTrans();
	}
	
	public function execute($sql)
	{
		return self::$connection->execute($sql);
	}
}